package top.rainbowecho.gateway.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import top.rainbowecho.gateway.security.property.SecurityProperties;

import java.util.ArrayList;
import java.util.List;

/**
 * @author rainbow
 * @since 2019/12/25 17:09
 */
@Configuration
@EnableAuthorizationServer
@RefreshScope
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    private AuthenticationManager authenticationManager;

    private UserDetailsService userDetailsService;

    private SecurityProperties securityProperties;

    private PasswordEncoder passwordEncoder;

    private TokenStore tokenStore;

    private JwtAccessTokenConverter tokenConverter;

    private TokenEnhancer tokenEnhancer;

    @Autowired
    public void setTokenEnhancer(TokenEnhancer tokenEnhancer) {
        this.tokenEnhancer = tokenEnhancer;
    }

    @Autowired
    public void setTokenConverter(JwtAccessTokenConverter tokenConverter) {
        this.tokenConverter = tokenConverter;
    }

    @Autowired
    public void setTokenStore(TokenStore tokenStore) {
        this.tokenStore = tokenStore;
    }

    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Autowired
    public void setSecurityProperties(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }

    @Autowired
    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Autowired
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancers = new ArrayList<>();
        enhancers.add(tokenEnhancer);
        enhancers.add(tokenConverter);
        enhancerChain.setTokenEnhancers(enhancers);

        endpoints.authenticationManager(this.authenticationManager)
                .userDetailsService(this.userDetailsService)
                .accessTokenConverter(this.tokenConverter)
                .tokenStore(this.tokenStore)
                .tokenEnhancer(enhancerChain);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        List<SecurityProperties.OAuth2ClientSecurityProperties> clientSecurityPropertiesList = this.securityProperties.getClients();

        InMemoryClientDetailsServiceBuilder inMemoryClientDetailsServiceBuilder = clients.inMemory();
        for (SecurityProperties.OAuth2ClientSecurityProperties oauth2Client : clientSecurityPropertiesList) {
            inMemoryClientDetailsServiceBuilder
                    .withClient(oauth2Client.getClientId())
                    // oauth2 2.x 版本中的client秘钥必须再进行加密
                    .secret(this.passwordEncoder.encode(oauth2Client.getClientSecret()))
                    .authorizedGrantTypes(oauth2Client.getGrantType())
                    .accessTokenValiditySeconds((int) oauth2Client.getTokenTimeout().getSeconds())
                    .refreshTokenValiditySeconds((int) oauth2Client.getRefreshTokenTimeout().getSeconds())
                    .scopes(oauth2Client.getScope());
        }

    }
}
